
from flask_restful import Resource, reqparse
import jwt

secret = 'secret'
algorithm = 'HS256'

parser = reqparse.RequestParser()
parser.add_argument('userid', type = int)
parser.add_argument('Authorization', location = 'headers', type = str)

class create_access_token(Resource):
    def post(self):
        try:                
            request = parser.parse_args()
            payload = {
                'data': {
                    'id': request['userid']
                }                    
            }
            access_token = jwt.encode(
                payload,
                secret,
                algorithm = algorithm,
            )
            return {
                'access_token': access_token
            }
        except Exception as e:
            return {
                "message": str(e)
            }


class verify_jwt_in_request(Resource):
    def get(self):
        try:
            request = parser.parse_args()
            payload = jwt.decode(
                request['Authorization'],
                secret,
                algorithms = algorithm,
            )
            if('data' in payload and 'id' in payload['data']):
                return {
                    "Valid": True,
                    "id": payload['data']['id']
                }
            else:
                return {
                    "Valid": False
                }
        except Exception as e:
            return {
                "message": str(e)
            }